import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/entity/user_center/coupon_list_entity.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

///我的优惠券控制器
class MyCouponController extends BaseController
    with SingleGetTickerProviderMixin {
  late TabController typeTabController;
  late TabController tabController;

  var typeList =[].obs;

  var dataList = [].obs;

  var page = 1.obs;

  int status = 0;

  int type = 0;

  bool hasNextPage = true;

  @override
  void onInit() {
    typeList.insert(0, {"label": "全部", "value": ""});
    typeList.insert(1, {"label": "全部", "value": ""});
    typeList.insert(2, {"label": "全部", "value": ""});
    typeList.insert(3, {"label": "全部", "value": ""});

    getCouponTypeAndNum();
    getMyCouponList();
    //---------优惠券类型---------
    typeTabController = TabController(length: 5, vsync: this);
    typeTabController.addListener(() {
      if (typeTabController.indexIsChanging) {
        // 当tab切换时执行的操作
        type = typeTabController.index;
        page.value = 1;
        getMyCouponList();
      }
    });
    //---------------------------
    //---使用类型----
    tabController = TabController(length: 3, vsync: this);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        // 当tab切换时执行的操作
        print("切换了状态，当前为状态为 index: ${tabController.index}");
        status = tabController.index;
        page.value = 1;
        getMyCouponList();
      }
    });
    //--------------
    super.onInit();
  }

  //获取可领取优惠券列表
  Future getMyCouponList() async {
    Tools.showLoading();
    Network.getMyCouponList(status, type, page.value, 10).then((value) {
      print(value);

      hasNextPage = value['hasNextPage'];
      if (page.value > 1) {
        dataList.addAll(value['list']);
      } else {
        dataList.value = value['list'];
      }

      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  //获取类型和数量
  Future getCouponTypeAndNum() async {
    Tools.showLoading();

    Network.getCouponReceiveNum().then((value) {
      // print(value);
      typeList.value = value;
      typeList.insert(0, {"label": "全部", "value": ""});
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    page.value = 1;
    await getMyCouponList();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
    if (hasNextPage) {
      page.value += 1;
      await getMyCouponList();
      baseRefreshCtr.loadComplete();
    }
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }
}
